﻿// ===============================================================================
// XCI.NET 西安交通信息WinForm开发框架 2018 版权所有
// ===============================================================================
using System;
using System.ComponentModel.DataAnnotations;
using XCI.Extensions;

namespace XCI.Annotations
{
    /// <summary>
    /// 与当前日期比较
    /// </summary>
    public class CompareNowDateAttribute : ValidationAttribute
    {
        /// <summary>
        /// 初始化与当前日期比较
        /// </summary>
        /// <param name="dateCompareType">日期比较类型</param>
        public CompareNowDateAttribute(DateCompareType dateCompareType, bool compareHms = false)
        {
            CompareType = dateCompareType;
            CompareHms = compareHms;
        }

        /// <summary>
        /// 是否比较时分秒
        /// </summary>
        public bool CompareHms { get; set; } = false;

        /// <summary>
        /// 日期比较类型
        /// </summary>
        public DateCompareType CompareType { get; private set; }

        /// <summary>
        /// 核心验证方法
        /// </summary>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value == null || value.IsEmpty()) return ValidationResult.Success;

            var displayName = validationContext.DisplayName;
            DateTime d1 = CompareHms ? DateTime.Now : DateTime.Now.Date;
            DateTime d2 = CompareHms ? value.ToDateTime(): value.ToDateTime().Date;

            #region CompareType

            switch (CompareType)
            {
                case DateCompareType.GreatThan:
                    if (!(d2 > d1))
                    {
                        return new ValidationResult(ErrorMessage ?? $"{displayName}必须大于当前日期");
                    }
                    break;
                case DateCompareType.GreatThanEquals:
                    if (!(d2 >= d1))
                    {
                        return new ValidationResult(ErrorMessage?? $"{displayName}必须大于等于当前日期");
                    }
                    break;
                case DateCompareType.LessThan:
                    if (!(d2 < d1))
                    {
                        return new ValidationResult(ErrorMessage?? $"{displayName}必须小于当前日期");
                    }
                    break;
                case DateCompareType.LessThanEquals:
                    if (!(d2 <= d1))
                    {
                        return new ValidationResult(ErrorMessage?? $"{displayName}必须小于等于当前日期");
                    }
                    break;
                case DateCompareType.Equals:
                    if (!(d2 == d1))
                    {
                        return new ValidationResult(ErrorMessage ?? $"{displayName}必须等于当前日期");
                    }
                    break;
            }

            #endregion

            return ValidationResult.Success;
        }
    }
}